import Layout from '@components/layout';
import { User as ListApi } from '@lib/api/work';
import { IUser, IWork } from '@lib/types';
import { workAs, workHref } from '@lib/url';
import { Alert, Button, Card, Table } from 'antd';
import Link from 'next/link';
import * as React from 'react';
import { connect } from 'react-redux';

interface IWorkProps {
	user: IUser;
}

interface IWorkState {
	work: IWork[];
	loading: boolean;
}

class Work extends React.Component<IWorkProps, IWorkState> {
	constructor(props: any) {
		super(props);
		this.state = {
			work: [],
			loading: true
		};
	}
	public async tryLoad() {
		if (this.props.user && this.state.work.length === 0) {
			const res = await ListApi(this.props.user.id);
			if (!(res instanceof Error)) {
				this.setState({
					loading: false,
					work: res.list
				});
			}
		}
	}
	public componentDidMount() {
		this.tryLoad();
	}
	public componentDidUpdate() {
		this.tryLoad();
	}
	public render() {
		const columns = [{
			title: "#",
			dataIndex: 'id',
			key: 'id',
			width: 35,
			render: (text: string) => text
		}, {
			title: "名称",
			dataIndex: 'name',
			key: 'name',
			render: (text: string, record: IWork) => (<Link href={workHref(record.id)} as={workAs(record.id)}><a>{text}</a></Link>)
		}, {
			title: "更新时间",
			dataIndex: 'update_time',
			key: 'update_time',
			className: 'hide-on-mobile',
			render: (text: string) => text
		}, {
			title: "简介",
			dataIndex: 'description',
			key: 'description',
			className: 'hide-on-mobile',
			render: (text: string) => text
		}, {
			title: "操作",
			key: 'action',
			width: 170,
			render: (_: string, record: IWork) => (
				<Button.Group>
					<Button><Link href={`/work/edit?id=${record.id}`}><a>编辑</a></Link></Button>
					<Button><Link href={`/work/upgrade?id=${record.id}`}><a>更新</a></Link></Button>
				</Button.Group>
			)
		}];
		return (
			<Layout title="我的作品">
				<Card title="我的作品">
					<Alert message={<span>您可以在<Link href="/my/profile"><a>个人设置</a></Link>中填写完善您的其他账号信息，方便玩家反馈问题</span>} type="info"></Alert>
					<p></p>
					<Table dataSource={this.state.work} columns={columns} loading={this.state.loading} rowKey="id" pagination={false}></Table>
				</Card>
			</Layout>
		);
	}
}


const mapStateToProps = (state: any) => ({
	user: state.user
});

export default connect(mapStateToProps)(Work);